const fs = require("fs");
const path = require("path")
const crypto = require("crypto");
const tinify = require("tinify");
const log = require('../../config/log').log;
const { preStatics, uploadPath, tinifyKey } = require("../../config/env");

tinify.key = tinifyKey;

class FileCtrl {
  /**
   * @api {post} /upload/:type 上传文件
   * @apiName /upload/images
   * @apiGroup upload
   * 
   * @apiHeader {String} vf token 
   * @apiParam {String} type 上传类型 [image, xiaohan, others]
   * 
   * @apiSuccessExample 返回示例
      HTTP/1.1 200 OK
      {
        errno: 0,
        data: "https://static.justdodo.cn/pig.png"
      }
   * @apiErrorExample 错误示例
      HTTP/1.1 500 Internal Server Error
  */
  async uploadImg(ctx, next) {
    const { type } = ctx.params;
    const Files = ctx.request.files;
    if (type !== 'images' && type !== 'others' && type !== 'xiaohan' && type !== 'zhangyue') {
      ctx.body = {
        errno: 1,
        msg: '暂不支持此类型文件!',
        data: null
      };
      return next();
    }
    if (!Files || !Files.file) {
      ctx.body = {
        errno: 1,
        msg: '上传文件为空!',
        data: null
      };
      return next();
    }
    let file = Files.file;
    const sha1 = crypto.createHash("sha1");
    sha1.update(file.name + file.size);
    const fileName = sha1.digest("hex");
    let files = fs.readdirSync(path.resolve(`${uploadPath}/${type}`)) || [];
    let isExit = files.indexOf(fileName) === -1 ? false : true;
    let ext = file.name.split(".").pop();
    if (!isExit) {
      const rs = fs.createReadStream(file.path);
      const ws = fs.createWriteStream(`${uploadPath}/${type}/${fileName}.${ext}`);
      rs.pipe(ws).on('close', () => {
        if(ext === 'jpg' || ext === 'jpeg' || ext === 'png') {
          const p = path.resolve(`${uploadPath}/${type}/${fileName}.${ext}`);
          tinify.fromFile(p).toFile(p).catch(err => {
            log(err, 'error')
          });
        }
      });
    }
    ctx.body = {
      errno: 0,
      data: [preStatics + "/" + type + "/" + fileName + "." + ext]
    };
    return next();
  }
}

module.exports = new FileCtrl();
